package com.example.config;

import com.example.domain.Order;
import com.example.enumm.OrderStatus;
import com.example.enumm.OrderStatusChangeEvent;
import com.example.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @description: 监听状态的变化：
 * @author: xukang
 * @create: 2025/6/18
 */
@Component("orderStateListener")
@WithStateMachine(name = "orderStateMachine")
@Slf4j
public class OrderStateListener {


    /**
     * 处理状态变更的通用逻辑
     *
     * @param message    状态变更消息
     * @param newStatus  新的状态
     * @param logMessage 日志信息
     */
    private void handleStatusChange(Message<OrderStatusChangeEvent> message, OrderStatus newStatus, String logMessage) {
        Order order = (Order) message.getHeaders().get("order");
        log.info("6.状态转换监听事件:{}，状态机反馈信息：{}", logMessage, order);
        // 更新订单状态
        // 此处order对象指向的是 MessageBuilder.setHeader时的order对象
        order.setStatus(newStatus.getKey());
        log.info("7.对象属性赋值,注意还未修改数据库（也可以在此处修改数据库）：{}", order);
        log.info("8.状态转换监听事件:{}，状态机变化新状态：{}", logMessage, newStatus.getDesc());

        //TODO 其他业务
        log.info("9.其他业务");
    }

    @OnTransition(source = "WAIT_PAYMENT", target = "WAIT_DELIVER")
    public void payTransition(Message<OrderStatusChangeEvent> message) {
        handleStatusChange(message, OrderStatus.WAIT_DELIVER, "支付");
    }

    @OnTransition(source = "WAIT_DELIVER", target = "WAIT_RECEIVE")
    public void deliverTransition(Message<OrderStatusChangeEvent> message) {
        handleStatusChange(message, OrderStatus.WAIT_RECEIVE, "发货");
    }

    @OnTransition(source = "WAIT_RECEIVE", target = "FINISH")
    public void receiveTransition(Message<OrderStatusChangeEvent> message) {
        handleStatusChange(message, OrderStatus.FINISH, "确认收货");
    }
}
